package com.atguigu.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.rabbit.consts.MqConst;
import com.atguigu.rabbit.service.RabbitService;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.utils.HttpRequestHelper;
import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.hosp.client.HospitalFeignClient;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.order.mapper.OrderInfoMapper;
import com.atguigu.yygh.order.service.OrderInfoService;
import com.atguigu.yygh.user.client.PatientFeignClient;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.atguigu.yygh.vo.order.OrderQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;


@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    PatientFeignClient patientFeignClient;

    @Autowired
    HospitalFeignClient hospitalFeignClient;

    @Autowired
    RabbitService rabbitService;

    //根据id查询订单详情
    @Override
    public OrderInfo getOrderInfo(Long id) {
        OrderInfo orderInfo = baseMapper.selectById(id);
//        Integer orderStatus = orderInfo.getOrderStatus();//订单状态
        return this.packOrderInfo(orderInfo);
    }


    @Override
    public Long saveOrder(String scheduleId, Long patientId) {
        //1.获取数据
        ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(scheduleId);
        Patient patient = patientFeignClient.getPatientById2(patientId);

        //2.封装医院端所需的参数
//        Map<String,Object> map = new HashMap<>();
//        map.put("hoscode",scheduleOrderVo.getHoscode());
//        map.put("depcode",scheduleOrderVo.getDepcode());
//        map.put("hosScheduleId",scheduleOrderVo.getHosScheduleId());
//        map.put("reserveDate",scheduleOrderVo.getReserveDate());
//        map.put("reserveTime",scheduleOrderVo.getReserveTime());
//        map.put("amount",scheduleOrderVo.getAmount());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode",scheduleOrderVo.getHoscode());
        paramMap.put("depcode",scheduleOrderVo.getDepcode());
        paramMap.put("hosScheduleId",scheduleOrderVo.getHosScheduleId());
        paramMap.put("reserveDate",new DateTime(scheduleOrderVo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", scheduleOrderVo.getReserveTime());
        paramMap.put("amount",scheduleOrderVo.getAmount()); //挂号费用
        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType",patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex",patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone",patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode",patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode",patient.getDistrictCode());
        paramMap.put("address",patient.getAddress());
        paramMap.put("contactsName",patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone",patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        paramMap.put("sign", "");

        //调用医院端接口
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, "http://localhost:9998/order/submitOrder");

        //医院端返回值
        if(result.getInteger("code") == 200){
            JSONObject jsonObject = result.getJSONObject("data");

            String hosRecordId = jsonObject.getString("hosRecordId");//医院端订单主键
            Integer number = jsonObject.getInteger("number");//预约序号
            String fetchTime = jsonObject.getString("fetchTime");//取号时间
            String fetchAddress = jsonObject.getString("fetchAddress");//取号地址

            //创建自己的订单
            OrderInfo orderInfo = new OrderInfo();

            BeanUtils.copyProperties(scheduleOrderVo, orderInfo);
            String outTradeNo = System.currentTimeMillis() + "" + new Random().nextInt(100);
            orderInfo.setOutTradeNo(outTradeNo);
            orderInfo.setScheduleId(scheduleId);
            orderInfo.setUserId(patient.getUserId());
            orderInfo.setPatientId(patientId);
            orderInfo.setPatientName(patient.getName());
            orderInfo.setPatientPhone(patient.getPhone());
            orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);

            baseMapper.insert(orderInfo);
            //7、利用mq更新mongodb中的数据
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            Integer availableNumber = jsonObject.getInteger("availableNumber");

            this.afterSaveOrder(reservedNumber,availableNumber,scheduleId,orderInfo);


            //返回订单号
            return orderInfo.getId();
        }else{
            throw new YyghException(20001,"预约挂号失败");
        }
    }

    private void afterSaveOrder(Integer reservedNumber,Integer availableNumber,String scheduleId,OrderInfo orderInfo){
        OrderMqVo orderMqVo = new OrderMqVo();
        orderMqVo.setAvailableNumber(availableNumber);
        orderMqVo.setReservedNumber(reservedNumber);
        orderMqVo.setScheduleId(scheduleId);//mongodb中的排班id

        MsmVo msmVo = new MsmVo();
        msmVo.setPhone(orderInfo.getPatientPhone());//就诊人手机号
        msmVo.setTemplateCode("模板");
        msmVo.getParam().put("message","【尚医通】挂号成功");

        orderMqVo.setMsmVo(msmVo);

        //发送mq
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.ROUTING_ORDER,orderMqVo);

    }


    /**
     * 订单列表
     * @param pageParam
     * @param orderQueryVo
     * @return
     */
    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> pageParam, OrderQueryVo orderQueryVo) {
        //获取条件值
        Long userId = orderQueryVo.getUserId();
//        String outTradeNo = orderQueryVo.getOutTradeNo();
        Long patientId = orderQueryVo.getPatientId();
//        String patientName = orderQueryVo.getPatientName();
        String name = orderQueryVo.getKeyword();
        String orderStatus = orderQueryVo.getOrderStatus();
        String reserveDate = orderQueryVo.getReserveDate();
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();


        //对条件值进行非空判断
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();

        if(!StringUtils.isEmpty(userId)) {
            wrapper.eq("user_id",userId);
        }
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("hosname",name);
        }
        if(!StringUtils.isEmpty(patientId)) {
            wrapper.eq("patient_id",patientId);
        }
        if(!StringUtils.isEmpty(orderStatus)) {
            wrapper.eq("order_status",orderStatus);
        }
        if(!StringUtils.isEmpty(reserveDate)) {
            wrapper.ge("reserve_date",reserveDate);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }

        Page<OrderInfo> pages = baseMapper.selectPage(pageParam, wrapper);

        //getRecords 提取数据
        pages.getRecords().forEach(item ->{
            this.packOrderInfo(item);
        });


        return pages;
    }

    private OrderInfo packOrderInfo(OrderInfo orderInfo){
        orderInfo.getParam().put("orderStatusString",OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }

}
